package cn.edu.bs.web.interceptor.permission;

import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * @author bs
 */
@Component
public class PermissionInterceptor extends HandlerInterceptorAdapter {

    private final static String ERROR_PATH = "/error";

    private final static String STATUS_ATTR = "javax.servlet.error.status_code";

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        String servletPath = request.getServletPath();
        HttpSession session = request.getSession();

        // 后台管理权限
        if (servletPath.startsWith("/admin")) {
            if (session.getAttribute("username") == null) {
                response.sendRedirect("/login");
                return false;
            } else if ("admin".equals(session.getAttribute("username"))) {
                return true;
            } else {
                forward(HttpStatus.FORBIDDEN.value(), request, response);
            }
        }

        if (servletPath.startsWith("/borrows")){
            if (session.getAttribute("username") == null) {
                response.sendRedirect("/login");
                return false;
            } else {
                return true;
            }
        }

        return false;
    }

    private void forward(Integer code, HttpServletRequest request, HttpServletResponse response) throws Exception {
        request.setAttribute(STATUS_ATTR, code);
        request.getRequestDispatcher(ERROR_PATH).forward(request, response);
    }
}
